package com.qf.web.config;


import cn.hutool.core.util.RandomUtil;
import com.qf.common.base.exception.ServiceException;
import com.qf.common.base.result.ResultCode;
import com.qf.web.common.vo.ShopkeeperVo;
import com.qf.web.common.qo.ShopkeeperRequestParams;
import com.qf.web.common.utils.ConstantUtils;
import com.qf.web.dao.BaseRedisDao;
import com.qf.web.entity.Shopkeeper;
import com.qf.web.service.ShopkeeperService;
import com.qf.web.service.impl.MsgServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

/**
 * 手机号加短信验证码校验
 * @author 51993
 */
public class UserCodeRealm extends AuthenticatingRealm {

    @Autowired
    ShopkeeperService shopkeeperService;

    @Autowired
    BaseRedisDao baseRedisDao;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //获取前端传过来的手机号
        String tel = (String) authenticationToken.getPrincipal();

        //去redis中取验证码
        String code = (String) baseRedisDao.getForValue(ConstantUtils.PHONE_LOGIN_KEY_PREFIX + tel);

        if (ObjectUtils.isEmpty(code)){
            //如果验证码为NULL，说明验证码已经到期，提示用户重新获取验证码
            throw new ServiceException(ResultCode.MSG_CODE_TIMEOUT);
        }

        //查询用户信息，并把它存储
        Shopkeeper shopkeeper = shopkeeperService.selectShopkeeperByPhone(tel);

        if (ObjectUtils.isEmpty(shopkeeper)){
            //用户不存在自动注册
            //随机生成商户名字
            String name = "鸽了么"+tel+ RandomUtil.randomNumbers(3);
            ShopkeeperRequestParams requestParams = new ShopkeeperRequestParams();
            requestParams.setShopkeeperPhone(tel);
            requestParams.setShopkeeperName(name);
            shopkeeperService.register(requestParams);
            shopkeeper = shopkeeperService.selectShopkeeperByPhone(tel);
        }

        ShopkeeperVo shopkeeperVo = new ShopkeeperVo();
        BeanUtils.copyProperties(shopkeeper,shopkeeperVo);

        //登录成功,把验证码从redis中移除
        baseRedisDao.delete(ConstantUtils.PHONE_LOGIN_KEY_PREFIX+tel);

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(shopkeeperVo, code, null, tel);

        return simpleAuthenticationInfo;
    }
}
